<template>
  <a-modal
    v-model:open="isOpen"
    :width="width"
    :title="title"
    :mask-closable="false"
    :afterClose="afterClose"
    :keyboard="false"
    :destroyOnClose="destroyOnClose"
    :okText="okText"
    :cancelText="cancelText"
    :closable="closable"
  >
    <template #footer>
      <template v-if="$slots.footer">
        <slot name="footer" />
      </template>
      <template v-else>
        <a-button @click="handleCancel" :disabled="isLoadingInner" v-if="isCancelButton">{{ cancelText }}</a-button>
        <a-button type="primary" :loading="isLoading" :disabled="isLoadingInner" @click="useBeforeChange" v-if="isOkButton">{{ okText }}</a-button>
      </template>
    </template>
    <div v-if="isLoadingInner" class="modal-content-loading">
      <a-spin :tip="innerLoadingTip" />
    </div>
    <template v-else>
      <slot />
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import { watch, ref, withDefaults } from "vue"
  import { useModalEvent } from "./use-modal-event"
  import { useModalMask } from "@/hook/index"
  import type { modalInstance } from "./instance"
  const props = withDefaults(defineProps<modalInstance>(), {
    width: "860px",
    okText: "确定",
    cancelText: "取消",
    isOkButton: true,
    isCancelButton: true,
    closable: true,
    footer: true,
    destroyOnClose: true,
    innerLoadingTip: "加载中...",
  })
  const emits = defineEmits(["update:open", "afterClose", "cancel", "ok"])
  // hook
  const { isLoading, isLoadingInner, useBeforeChange, useInnerLoading } = useModalEvent({ props })
  const { isMask, nextMaskIndex, initialization } = useModalMask()
  // ref
  const isOpen = ref(false)

  const afterClose = () => {
    nextMaskIndex("delete")
    close()
    emits("afterClose")
  }

  const handleCancel = () => {
    close()
  }

  const close = () => {
    emits("update:open", false)
    emits("cancel")
  }

  watch(
    () => props.open,
    (val) => {
      isOpen.value = val
      if (val) {
        nextMaskIndex()
        useInnerLoading()
      }
    }
  )
</script>
<style lang="scss" scoped>
  .modal-content-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    height: 100%;
  }
</style>
